<?php

namespace app\admin\controller;

use think\facade\View;
use think\facade\Request;
use app\admin\logic\order\ShipOrderLogic;
use app\common\model\order\ShipOrder as ShipOrderModel;
use app\common\ConstVar;
use app\common\service\Util;

class Shiporder extends Base
{
    /**
     * 船舶订单列表页面
     * 展示管理员后台船舶订单管理列表，包含订单状态统计信息
     * @return \think\response\View 渲染的订单列表页面视图
     */
    public function shiporderlist()
    {
        $orderStatusCounts = ShipOrderLogic::getNoticeCounts();
        View::assign('ShipOrderStatus', ConstVar::$OrderStatus);
        View::assign('statusCounts', $orderStatusCounts);
        return View::fetch();
    }

    /**
     * 获取船舶订单JSON列表数据
     * 用于管理员后台船舶订单管理页面的数据展示，支持多条件筛选
     * @return string JSON格式的订单列表数据，包含总数和分页数据
     * @throws Exception 当数据库查询失败时抛出异常
     */
    public function shiporderjsonlists()
    {
        $param = Request::get();
        $param['contact_name'] = trim(Request::param('contact_name', ''));
        $param['tc_order_no'] = trim(Request::param('tc_order_no', ''));
        $param['booking_tel'] = trim(Request::param('booking_tel', ''));

        // 调用逻辑层获取订单列表数据
        $result = ShipOrderLogic::getShipOrderList($param);

        // list为空时，message提示暂无数据
        if (empty($result['list'])) {
            return $this->genTableJson($result['paginator'], [], 0, '暂无数据');
        }

        // 生成表格JSON响应
        return $this->genTableJson($result['paginator'], $result['list']);
    }

    /**
     * 编辑船舶订单详情
     * 获取订单详细信息并解析JSON字段，准备编辑页面所需数据
     * @return \think\response\View 渲染的订单编辑页面视图
     */
    public function shiporderedit()
    {
        $param = Request::instance()->param();
        $result = ShipOrderLogic::getShipOrderDetail($param);

        if (empty($result)) {
            return $this->errorJump('订单不存在', url('shiporder/shiporderlist'), 5);
        }

        // 处理订单状态选项
        $status = ConstVar::$OrderStatus;
        if (!in_array($result['shiporder']['status'], [6, 1, 2])) {
            unset($status[6], $status[1], $status[2]);
        }

        View::assign([
            'shiporder' => $result['shiporder'],
            'changeVoyages' => $result['changeVoyages'],
            'shiporder_take_children' => $result['take_children'],
            'refundInfo' => $result['refundInfo'],
            'OrderStatus' => $status
        ]);

        return View::fetch();
    }

    /**
     * 删除船舶订单
     * 根据订单ID从数据库中删除指定船舶订单
     * @return \think\response\Json 包含删除结果的JSON响应
     */
    public function shiporderdel()
    {
        $shiporder_id = Request::param('id');
        ShipOrderModel::where('id', $shiporder_id)->delete();
        $this->successJump('删除成功', url('shiporder/shiporderlist'), 5);
    }

    /**
     * 标记订单为已读
     * 更新订单的is_read状态为1，表示该订单已被查看
     * @return \think\response\Json 包含操作结果的JSON响应
     */
    public function shiporderread()
    {
        $shiporder_id = Request::param('id');
        ShipOrderModel::where('shiporder_id', $shiporder_id)
            ->update(['is_read' => 1]);
        $this->successJump('成功', url('shiporder/shiporderlist'), 5);
    }

    /**
     * 处理退款请求
     * 根据订单ID和退款金额执行船舶订单退款操作
     * @return \think\response\Json 包含退款结果的JSON响应
     */
    public function refund()
    {
        $shiporder_id = intval(Request::param('id', 0));
        $refund_money = floatval(Request::param('refund_money', 0));
        $shiporder = ShipOrderModel::where('shiporder_id', $shiporder_id)->find();
        if (!$shiporder) {
            return Util::ajaxReturn(1, "订单错误");
        }
        if (!in_array($shiporder['status'], [6, 8, 9, 10])) {
            return Util::ajaxReturn(0, "订单状态错误");
        }

        if ($refund_money == 0) {
            return Util::ajaxReturn(0, "退款金额不能为0");
        }
        if ($refund_money > floatval($shiporder['total'])) {
            return Util::ajaxReturn(0, "退款金额不能订单金额");
        }

        $shiporder['notify_data'] = json_decode($shiporder['notify_data'], true);
        $shiporder['contact_list'] = json_decode($shiporder['contact_list'], true);
        $shiporder['chooseSeat'] = json_decode($shiporder['chooseSeat'], true);
        $shiporder['chooseFlight'] = json_decode($shiporder['chooseFlight'], true);
        $shiporder['shipline'] = json_decode($shiporder['shipline'], true);

        //退款操作
        if ($shiporder['pay_type'] == 1) {
            $selft_refund_no = $shiporder['selft_refund_no'] ? $shiporder['selft_refund_no'] : uniqid();
            $refundParams = [
                'transaction_id' => $shiporder['notify_data']['transaction_id'],
                'out_refund_no' => $selft_refund_no,
                'total_fee' => $shiporder['notify_data']['total_fee'],
                'refund_fee' => (int)($refund_money * 100)
            ];
            $result = \app\common\service\third_party_api\PayApiService::wxRefund($refundParams);
            if (isset($result['result_code']) && $result['result_code'] == 'SUCCESS') {
                ShipOrderModel::where([
                    ['shiporder_id', '=', $shiporder_id],
                ])->update([
                    'refund_time' => time(),
                    'refund_money' => $refund_money,
                    'selft_refund_no' => $selft_refund_no,
                    'status' => 5,
                    'refund_response' => json_encode($result),
                ]);
                return Util::ajaxReturn(1, "退款成功");
            } else {
                ShipOrderModel::where([
                    ['shiporder_id', '=', $shiporder_id],
                ])->update([
                    'status' => 9,
                    'refund_response' => json_encode($result),
                    'selft_refund_no' => $selft_refund_no,
                ]);
                return Util::ajaxReturn(0, "退款失败");
            }
        } elseif ($shiporder['pay_type'] == 2) {
            if (!empty($shiporder['shiporder_id'])) {
                // 构建退款参数
                $refundParams = [
                    'out_trade_no' => !empty($shiporder['out_trade_no']) ? $shiporder['out_trade_no'] : trim($shiporder['shiporder_id']),
                    'refund_amount' => $refund_money,
                    'refund_reason' => '测试退款',
                    'out_request_no' => trim($shiporder['shiporder_id'])
                ];

                // 调用第三方支付插件的支付宝退款方法
                $result = \app\common\service\third_party_api\PayApiService::aliRefund($refundParams);
                if ($result['code'] == '10000') {
                    ShipOrderModel::where([
                        ['shiporder_id', '=', $shiporder_id],
                    ])->update([
                        'refund_time' => time(),
                        'refund_money' => $result['refund_fee'],
                        'selft_refund_no' => $result['trade_no'],
                        'status' => 5,
                        'refund_response' => json_encode($result),
                    ]);
                    return Util::ajaxReturn(1, "退款成功");
                } else {
                    ShipOrderModel::where([
                        ['shiporder_id', '=', $shiporder_id],
                    ])->update([
                        'status' => 9,
                        'refund_response' => json_encode($result)
                    ]);
                    return Util::ajaxReturn(0, "退款失败");
                }
            }
        } else {
            ShipOrderModel::where([
                ['shiporder_id', '=', $shiporder_id],
            ])->update([
                'status' => 9,
                'refund_response' => '支付类型错误',
            ]);
        }
        return Util::ajaxReturn(0, "系统错误");
    }
}
